/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.khstudio.api.dialog;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.khstudio.api.R;

public class KhDialogFileEditor extends KhDialog {
    private String              mEdit;
    private String              mHint;
    private String              mPositive;
    private String              mNegative;
    private String              mCancel;

    private EditText            mEditTextView;

    public static KhDialogFileEditor show(Activity a,
                                          int id, int titleResId,
                                          String edit, int hintResId,
                                          int positiveResId,
                                          int negativeResId,
                                          int cancelResId) {
        FragmentManager     fm = a.getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        Fragment prev = fm.findFragmentByTag("khdialogfileeditor");

        Resources           r = a.getResources();

        if (prev != null) {
            ft.remove(prev);
        }

        Bundle args = new Bundle();
        args.putInt("id", id);

        if(titleResId > 0) {
            args.putString("title", r.getString(titleResId));
        }
        if(hintResId > 0) {
            args.putString("hint", r.getString(hintResId));
        }
        if(positiveResId > 0) {
            args.putString("positive", r.getString(positiveResId));
        }
        if(negativeResId > 0) {
            args.putString("negative", r.getString(negativeResId));
        }
        if(cancelResId > 0) {
            args.putString("cancel", r.getString(cancelResId));
        }

        // Create and show the dialog.
        KhDialogFileEditor f = new KhDialogFileEditor();
        f.setEditText(edit);
        f.setArguments(args);
        f.show(ft, "khdialogfileeditor");

        return f;
    }

    public static KhDialogFileEditor show(FragmentManager fm,
                                          int id, String title,
                                          String edit, String hint,
                                          String positive,
                                          String negative,
                                          String cancel) {
        FragmentTransaction ft = fm.beginTransaction();
        Fragment prev = fm.findFragmentByTag("khdialogfileeditor");

        if (prev != null) {
            ft.remove(prev);
        }

        Bundle args = new Bundle();
        args.putInt("id", id);
        if(title != null) {
            args.putString("title", title);
        }
        if(hint != null) {
            args.putString("hint", hint);
        }
        if(positive != null) {
            args.putString("positive", positive);
        }
        if(negative != null) {
            args.putString("negative", negative);
        }
        if(cancel != null) {
            args.putString("cancel", cancel);
        }

        // Create and show the dialog.
        KhDialogFileEditor f = new KhDialogFileEditor();
        f.setEditText(edit);
        f.setArguments(args);
        f.show(ft, "khdialogfileeditor");

        return f;
    }

    public void setEditText(String text) {
        mEdit = text;
        if(mEditTextView != null) {
            mEditTextView.setText(mEdit);
        }
    }

    public String getEditText() {
        return mEditTextView.getText().toString();
    }

    public KhDialogFileEditor() {
        super();

        mEdit     = null;
        mHint     = null;
        mPositive = null;
        mNegative = null;
        mCancel   = null;

        mEditTextView = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHint     = getArguments().getString("hint", null);
        mPositive = getArguments().getString("positive", null);
        mNegative = getArguments().getString("negative", null);
        mCancel   = getArguments().getString("cancel", null);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString("edit", mEditTextView.getText().toString());
        outState.putInt("editselectionstart", mEditTextView.getSelectionStart());
        outState.putInt("editselectionend", mEditTextView.getSelectionEnd());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if(mTitle != null) {
            getDialog().setTitle(mTitle);
        }

        View v = _createViewFileEditor(getActivity());

        if (savedInstanceState != null) {
            mEdit = savedInstanceState.getString("edit", null);
            int selectionStart = savedInstanceState.getInt("editselectionstart", -1);
            int selectionEnd = savedInstanceState.getInt("editselectionend", -1);
            if(mEdit != null) {
                mEditTextView.setText(mEdit);
                mEditTextView.setSelection(selectionStart, selectionEnd);
            }
        } else {
            if(mEdit != null) {
                int separatorIndex = mEdit.lastIndexOf('.');
                separatorIndex = (separatorIndex < 0) ? mEdit.length() : separatorIndex;
                mEditTextView.setText(mEdit);
                mEditTextView.setSelection(0, separatorIndex);
            }
        }

        new Handler().postDelayed(new Runnable(){
            public void run(){
                InputMethodManager mgr = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                mgr.showSoftInput(mEditTextView, InputMethodManager.SHOW_IMPLICIT);
            }
            }, 100 );

        return v;
    }

    private View _createViewFileEditor(Context context) {
        float dip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getActivity().getResources().getDisplayMetrics());

        LinearLayout ll = new LinearLayout(context);
        ll.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setGravity(Gravity.CENTER_HORIZONTAL);
        ll.setPadding((int) (10 * dip), (int) (15 * dip), (int) (10 * dip), (int) (4 * dip));

        mEditTextView = new EditText(context);
        mEditTextView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        mEditTextView.setPadding((int) (10 * dip), (int) (10 * dip), (int) (10 * dip), (int) (5 * dip));
        mEditTextView.setTextAppearance(getActivity(), android.R.style.TextAppearance_DeviceDefault_Medium);
        mEditTextView.setPrivateImeOptions("inputType=filename;defaultInputmode=english");
        mEditTextView.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

        if(mHint != null) mEditTextView.setHint(mHint);
        mEditTextView.requestFocus();

        ll.addView(mEditTextView);

        ll.addView(_createButton(context));

        return ll;
    }

    private View _createButton(Context context) {
        float dip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getActivity().getResources().getDisplayMetrics());
        Button btn = null;

        LinearLayout ll = new LinearLayout(getActivity());
        ll.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setPadding(0, (int) (15 * dip), 0, 0);

        if(mPositive != null) {
            btn = new Button(context);
            btn.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
            btn.setBackgroundResource(R.drawable.kh_btn_selector);
            btn.setText(mPositive);
            btn.setVisibility(View.VISIBLE);
            btn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mListener != null) mListener.onPositiveClick(mId);
                }
            });
            ll.addView(btn);
        }

        if(mNegative != null) {
            btn = new Button(context);
            btn.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
            btn.setBackgroundResource(R.drawable.kh_btn_selector);
            btn.setText(mNegative);
            btn.setVisibility(View.VISIBLE);
            btn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mListener != null) mListener.onNegativeClick(mId);
                }
            });
            ll.addView(btn);
        }

        if(mCancel != null) {
            btn = new Button(context);
            btn.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
            btn.setBackgroundResource(R.drawable.kh_btn_selector);
            btn.setText(mCancel);
            btn.setVisibility(View.VISIBLE);
            btn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(mListener != null) mListener.onCancelClick(mId);
                }
            });
            ll.addView(btn);
        }

        return ll;
    }

}
